package queue

import (
	"code.alibaba-inc.com/agit/quarantine-helper/utils"
)

// Commit is a wrap struct for *git.Commit
type Commit struct {
	commit *utils.GitCommit
}

// CreateCommitStruct create a Commit object from a *git.Commit object
func CreateCommitStruct(commit *utils.GitCommit) Commit {
	return Commit{commit: commit}
}

// GetCommit returns field commit of struct Commit
func (cm *Commit) GetCommit() *utils.GitCommit {
	return cm.commit
}

// PriorityQueue is the underlayer data structure type for the heap
type PriorityQueue []*Commit

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(a, b int) bool {
	timeA := pq[a].GetCommit().Committer.Date
	timeB := pq[b].GetCommit().Committer.Date
	return timeA.After(timeB)
}

func (pq PriorityQueue) Swap(a, b int) {
	pq[a], pq[b] = pq[b], pq[a]
}

// Push is the underlayer function that is called by heap.Push
func (pq *PriorityQueue) Push(x interface{}) {
	item := x.(*Commit)
	*pq = append(*pq, item)
}

// Pop is the underlayer function that is called by heap.Pop
func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	commit := old[n-1]
	old[n-1] = nil
	*pq = old[0 : n-1]
	return commit
}
